{extend name="app/shop/view/base.html"/}
{block name="resources"}
{/block}
{block name="main"}

<div class="layui-form form-wrap">

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>套餐名称：</label>
		<div class="layui-input-inline">
			<input type="text" name="recharge_name" lay-verify="required" value="{$recharge.data.recharge_name}" autocomplete="off" class="layui-input len-long" maxlength="40">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">封面：</label>
		<div class="layui-input-inline img-upload">
			<div class="upload-img-block icon">
				<div class="upload-img-box {if condition="$recharge.data.cover_img"}hover{/if}">
					<div class="upload-default" id="img">
					{if condition="$recharge.data.cover_img"}
						<div id="preview_img" class="preview_img">
							<img layer-src src="{:img($recharge.data.cover_img)}"  class="img_prev"/>
						</div>
					{else/}
						<div class="upload">
							<i class="iconfont iconshangchuan"></i>
							<p>点击上传</p>
						</div>
					{/if}
					</div>
					<div class="operation">
						<div>
                            <i title="图片预览" class="iconfont iconreview js-preview" style="margin-right: 20px;"></i>
                            <i title="删除图片" class="layui-icon layui-icon-delete js-delete"></i>
						</div>
						
						<div class="replace_img js-replace">点击替换</div>
					</div>
					<input type="hidden" class="layui-input" name="cover_img" value="{$recharge.data.cover_img}" />
				</div>
				<!-- <p id="img" class=" {if condition="$recharge.data.cover_img"} replace {else/} no-replace{/if}">替换</p>
				<input type="hidden" class="layui-input" name="cover_img" value="{$recharge.data.cover_img}" />
				<i class="del {if condition="$recharge.data.cover_img"}show{/if}">x</i> -->
			</div>
		</div>
	</div>
	<!--<div class="layui-form-item">-->
		<!--<label class="layui-form-label">封面：</label>-->
		<!--<input type="hidden" class="layui-input" name="cover_img" value="{$recharge.data.cover_img}" />-->
		<!--<div class="layui-input-inline img-upload">-->
			<!--<div class="upload-img-block icon">-->
				<!--<div class="upload-img-box" id="redPacket">-->
					<!--<img src="{:img($recharge.data.cover_img)}" />-->
				<!--</div>-->
			<!--</div>-->
		<!--</div>-->
	<!--</div>-->
	<input type="hidden" name="recharge_id" value="{$recharge.data.recharge_id}">
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>面值：</label>
		<div class="layui-input-inline">
			<input type="number" name="face_value" lay-verify="required|sum|number" value="{$recharge.data.face_value}" autocomplete="off" class="layui-input len-short" onblur="checkInput(this)">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>价格：</label>
		<div class="layui-input-inline">
			<input type="number" name="buy_price" lay-verify="required|sum|number" value="{$recharge.data.buy_price}" autocomplete="off" class="layui-input len-short" onblur="checkInput(this)">
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>赠送积分：</label>
		<div class="layui-input-inline">
			<input type="number" name="point" lay-verify="required|num|number" value="{$recharge.data.point}" autocomplete="off" class="layui-input len-short" onblur="checkInput(this)">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>赠送成长值：</label>
		<div class="layui-input-inline">
			<input type="number" name="growth" lay-verify="required|num|number" value="{$recharge.data.growth}" autocomplete="off" class="layui-input len-short" onblur="checkInput(this)">
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">赠送优惠券：</label>
		<div class="layui-input-block">
			<div class="coupon-item coupon">
				<div class="discount-cont">
					<div><a href="javascript:;" class="text-color select-coupon">选择优惠券</a></div>
					<div class="word-aux" style="margin-left: 0">
						<p>活动优惠券发放，不受优惠券自身数量和领取数量的限制</p>
					</div>
					<div>
						<table class="layui-table" lay-skin="nob">
							<colgroup>
								<col width="30%">
								<col width="50%">
								<col width="20%">
							</colgroup>
							<thead>
								<tr>
									<th>优惠券</th>
									<th>优惠内容</th>
									<th style="text-align:center;">操作</th>
								</tr>
							</thead>
							<tbody>
								{if isset($recharge.data.coupon_list) && !empty($recharge.data.coupon_list)}

								{foreach $recharge.data.coupon_list as $k => $vo}
								<tr data-coupon="{$vo.coupon_type_id}">
									<td>{$vo.coupon_name }</td>
									{if $vo.at_least > 0 }
									<td>满{$vo.at_least }{$vo.type == 'discount' ? '打'. $vo.discount .'折' : '减' . $vo.money }</td>
									{else/}
									<td>无门槛，{$vo.type == 'discount' ? '打'. $vo.discount .'折' : '减' . $vo.money }</td>
									{/if}
									<td style="text-align:center;"><a href="javascript:;" onclick="deleteCoupon(this)" class="text-color">删除</a></td>
								</tr>
								{/foreach}

								{/if}
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="form-row">
		<button class="layui-btn" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		<a id="coverImgId"></a>
	</div>
</div>
{/block}
{block name="script"}
<script>
    var coupon_list = '{$recharge.data.coupon_id}',laytpl;
	var saveData = null;
	var totalUploadNum = 0;
	var completeUploadNum = 0;
	var upload;

	layui.use(['form', 'laytpl'], function() {
		var form = layui.form,
			repeat_flag = false; //防重复标识
	        laytpl = layui.laytpl;
            form.render();
		/**
		 * 表单验证
		 */
		form.verify({
			num: function(value) {
				if (value < 0 || value % 1 != 0) {
					return '请输入正整数！';
				}
			},
			number: function (value) {
				if (value < 0) {
					return '请输入不小于0的数!'
				}
			},
			sum: function (value) {
				var arrMen = value.split(".");
				var val = 0;
				if (arrMen.length == 2) {
					val = arrMen[1];
				}
				if (val.length > 2) {
					return '保留小数点后两位'
				}
			}
		});

		upload = new Upload({
			elem: '#img',
			auto:false,
			bindAction:'#coverImgId',
			callback: function(res) {
				uploadComplete('cover_img', res.data.pic_path);
			}
		});

		function uploadComplete(field, pic_path) {
			saveData.field[field] = pic_path;
			completeUploadNum += 1;
			if(completeUploadNum == totalUploadNum){
				saveFunc();
			}
		}

		function saveFunc(){
			var data = saveData;
			// 删除图片
			if(!data.field.cover_img) upload.delete();

			$.ajax({
				type: "POST",
				url: ns.url("memberrecharge://shop/memberrecharge/edit"),
				data: data.field,
				dataType: 'JSON',
				success: function(res){
					repeat_flag = false;

					if (res.code == 0) {
						layer.confirm('编辑成功', {
							title:'操作提示',
							btn: ['返回列表', '继续操作'],
							yes: function(){
								location.href = ns.url("memberrecharge://shop/memberrecharge/lists");
							}
						});
					}else{
						layer.msg(res.message);
					}
				}
			});
		}
		
		form.on('submit(save)', function(data){
			data.field.coupon_id = coupon_list;

			if (repeat_flag) return false;
			repeat_flag = true;

			saveData = data;
			var obj = $("img.img_prev[data-prev='1']");
			totalUploadNum = obj.length;
			if(totalUploadNum > 0){
				obj.each(function(){
					var actionId = $(this).attr('data-action-id');
					$(actionId).click();
				})
			}else{
				saveFunc();
			}
		});
		form.on('submit(coupon-search)', function(data) {
			couponTable.reload({
				page: {
					curr: 1
				},
				where: data.field
			})
		});
	});

    // 选择优惠
    $('body').on('click', '.coupon-item .layui-form-checkbox', function(e){
        if ($(this).prev('[name="discount_type"]').is(':checked')) {
            $(this).parents('.coupon-item').find('.discount-cont').removeClass('layui-hide');
        } else {
            $(this).parents('.coupon-item').find('.discount-cont').addClass('layui-hide');
        }
    })

    $('body').on('click', '.coupon-item .select-coupon', function(e){
        var event = this;

        layer.open({
            type: 1,
            area: ["1200px","800px"],
            title: '优惠券列表',
            skin: 'select-coupon-layer',
            content: $("#couponList").html()
        });

        couponTable = new Table({
            elem: "#coupon_list",
            url: ns.url("coupon://shop/coupon/lists"),
            where: {'status': 1},
            cols: [
                [{
                    title: '优惠券名称',
                    unresize: 'false',
                    width: '15%',
                    templet: '#couponName'
                }, {
                    title: '类型',
                    unresize: 'false',
                    width: '10%',
                    templet: function(data){
                        return data.type == 'discount' ? '折扣' : '满减'
                    }
                }, {
                    title: '优惠金额/折扣',
                    unresize: 'false',
                    width: '15%',
					templet: function(data){
						return data.type == 'discount' ? data.discount+'折' : data.money+'元';
					}
                }, {
					field: 'goods_type',
					title: '适用商品',
					unresize: 'false',
					width: '10%',
					templet: function (data) {
						if (data.goods_type == 1) {
							return '全部商品';
						} else if (data.goods_type == 2) {
							return '指定商品';
						} else if (data.goods_type == 3) {
							return '指定不参与商品';
						}
					}
				},{
					field: 'max_fetch',
					title: '领取人限制',
					unresize: 'false',
					width: '10%'
				},{
                    field: 'count',
                    title: '已领取/发放数',
                    unresize: 'false',
                    width: '15%',
					templet: function(data){
						return data.count == -1 ? data.lead_count+'/不限量' : data.lead_count+'/'+data.count;
					}
                },  {
                    field: 'gift_state',
                    title: '结束时间',
                    unresize: 'false',
                    width: '15%',
                    templet: function (res) {
                        if(res.validity_type == 0){
							return ns.time_to_date(res.end_time);
                        }else{
							return "领取之日起" + res.fixed_term + "天有效";
                        }
                    }
                }, {
                    title: '操作',
                    toolbar: '#couponOperation',
                    unresize: 'false',
					align:'right'
                }]
            ]
        });

        couponTable.tool(function(obj) {
            var data = obj.data;
            switch (obj.event) {
                case "add":
                    addcoupon(data);
                    break;
            }
        });

        function addcoupon(data){
            var template = `<tr data-coupon="{{ d.coupon_type_id }}">
				<td>{{ d.coupon_name }}</td>
				{{# if(d.at_least > 0){  }}
					<td>满{{ d.at_least }}{{ d.type == 'discount' ? '打'+ d.discount +'折' : '减' + d.money }}</td>
				{{# } else { }}
					<td>无门槛，{{ d.type == 'discount' ? '打'+ d.discount +'折' : '减' + d.money }}</td>
				{{# } }}
				<td style="text-align:center;"><a href="javascript:;" onclick="deleteCoupon(this)" class="text-color">删除</a></td>
			</tr>`;
            laytpl(template).render(data, function(string){
                $(event).parents('.discount-cont').find('.layui-table tbody').append(string);
                layer.closeAll();
            });
            getCoupon();
        }
    })

    // 删除优惠券
    function deleteCoupon(e){
        $(e).parents('tr').remove();
        getCoupon();
    }

    //获取已选中优惠券
    function getCoupon() {
        var coupon = [];
        $('.coupon').find('tr[data-coupon]').each(function (i, e) {
            coupon.push($(e).attr('data-coupon'));
        })
        coupon_list = coupon.toString();
    }

	function back() {
		location.href = ns.url("memberrecharge://shop/memberrecharge/lists");
	}
	function checkInput(obj){
		$(obj).val(Math.abs($(obj).val()));
	}
</script>

<!-- 优惠券 -->
<script type="text/html" id="couponList">
	<div class="gift-box">
		<div class="single-filter-box">
			<div class="layui-form">
				<div class="layui-input-inline">
					<input type="text" name="coupon_name" placeholder="请输入优惠券名称" class="layui-input len-mid">
					<button type="button" class="layui-btn layui-btn-primary" lay-filter="coupon-search" lay-submit>
						<i class="layui-icon">&#xe615;</i>
					</button>
				</div>
			</div>
		</div>
		<table id="coupon_list" lay-filter="coupon_list"></table>
	</div>
</script>

<!-- 优惠券-名称 -->
<script type="text/html" id="couponName">
	<div class="table-tuwen-box">
		<div class="font-box">
			<p class="multi-line-hiding">{{d.coupon_name}}</p>
		</div>
	</div>
</script>

<!-- 优惠券-操作 -->
<script type="text/html" id="couponOperation">
	{{# var select_coupon_list = ','+coupon_list+','}}
	{{# if(select_coupon_list.indexOf(','+d.coupon_type_id+',') != -1){ }}
	<p title="该优惠券已参加">已添加</p>
	{{# }else{ }}
	<a class="layui-btn" lay-event="add">添加</a>
	{{# } }}
</script>
{/block}